package com.tts.service;

import com.tts.entity.Book;
import com.tts.entity.BorrowRecord;
import com.tts.entity.User;
import com.tts.exception.BusinessException;
import com.tts.repository.BookRepository;
import com.tts.repository.BorrowRecordRepository;
import com.tts.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BorrowService {

    @Autowired
    private BorrowRecordRepository borrowRecordRepository;

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private UserRepository userRepository;

    public List<BorrowRecord> getCurrentUserBorrowRecords() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));
        return borrowRecordRepository.findByUserId(user.getId());
    }

    @Transactional
    public BorrowRecord borrowBook(Long bookId) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new BusinessException("图书不存在"));

        if (book.getStock() <= 0) {
            throw new BusinessException("图书库存不足");
        }

        // 检查用户当前借阅数量
        long currentBorrows = borrowRecordRepository.countCurrentBorrowsByUserId(user.getId());
        if (currentBorrows >= 5) {
            throw new BusinessException("已达到最大借阅数量限制(5本)");
        }

        book.setStock(book.getStock() - 1);
        book.setBorrowTimes(book.getBorrowTimes() + 1);
        bookRepository.save(book);

        BorrowRecord borrowRecord = new BorrowRecord();
        borrowRecord.setUser(user);
        borrowRecord.setBook(book);
        borrowRecord.setBorrowTime(LocalDateTime.now());
        borrowRecord.setShouldReturnTime(LocalDateTime.now().plusDays(30)); // 设置30天的借阅期限
        borrowRecord.setStatus(BorrowRecord.BorrowStatus.BORROWED);
        borrowRecord.setCreatedTime(LocalDateTime.now());
        borrowRecord.setUpdatedTime(LocalDateTime.now());

        return borrowRecordRepository.save(borrowRecord);
    }

    @Transactional
    public BorrowRecord returnBook(Long recordId) {
        BorrowRecord record = borrowRecordRepository.findById(recordId)
                .orElseThrow(() -> new BusinessException("借阅记录不存在"));

        if (record.getStatus() == BorrowRecord.BorrowStatus.RETURNED) {
            throw new BusinessException("图书已归还");
        }

        Book book = record.getBook();
        book.setStock(book.getStock() + 1);
        bookRepository.save(book);

        record.setReturnTime(LocalDateTime.now());
        record.setStatus(BorrowRecord.BorrowStatus.RETURNED);
        record.setUpdatedTime(LocalDateTime.now());
        return borrowRecordRepository.save(record);
    }
} 